package gtug.duesseldorf.server;

import gtug.duesseldorf.client.util.StringUtils;

import java.io.IOException;
import java.text.MessageFormat;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.zschech.gwt.comet.server.CometServlet;
import net.zschech.gwt.comet.server.CometServletResponse;
import net.zschech.gwt.comet.server.CometSession;

public class WaveCometServlet extends CometServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void doComet(CometServletResponse cometResponse) throws ServletException, IOException {
		HttpServletRequest request = cometResponse.getRequest();
		final String clientId = StringUtils.trimToNull(request.getParameter("clientId"));
		if (clientId == null) {
			cometResponse.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, "No clientId provider");
			return;
		}

		Client c = ClientPool.getClient(clientId);
		if (c == null) {
			cometResponse.sendError(HttpServletResponse.SC_EXPECTATION_FAILED, MessageFormat.format("No client with id={0} available",
					new Object[] { clientId }));
			return;
		}

		CometSession cometSession = cometResponse.getSession();
		c.registerConnection(cometSession);
	}

}
